<?php

namespace Payment\Notify;

use Payment\Common\LTFConfig;
use Payment\Common\PayException;
use Payment\Config;
use Payment\Utils\ArrayUtil;

class LTFNotify extends NotifyStrategy{

	/**
	 * SwNotify constructor.
	 *
	 * @param array $config
	 * @throws PayException
	 */
	public function __construct(array $config){
		parent::__construct($config);
		try{
			$this->config = new LTFConfig($config);
		}catch(PayException $e){
			throw $e;
		}
	}

	/**
	 * 获取移除通知的数据  并进行简单处理（如：格式化为数组）
	 * 如果获取数据失败，返回false
	 *
	 * @return array|false
	 */
	public function getNotifyData(){
		$params = array();

		//支持直接读取input流
		$data = @file_get_contents('php://input');
		if(!empty($data)){
//			$inputArray = json_decode($data, true);
			parse_str($data,$inputArray);
			$params = array_merge($params, $inputArray);
		}

		if(count($params) < 1){//如果参数为空,则不进行处理
			return false;
		}

		return $params;
		// TODO: Implement getNotifyData() method.
	}

	/**
	 * 检查异步通知的数据是否合法
	 * 如果检查失败，返回false
	 *
	 * @param array $data 由 $this->getNotifyData() 返回的数据
	 * @return boolean
	 * @throws \Exception
	 */
	public function checkNotifyData(array $data){
		if($data['code'] != 'SUCCESS') return false;
		return $this->verifySign($data);
		// TODO: Implement checkNotifyData() method.
	}

	/**
	 * 检查数据是否被篡改过
	 *
	 * @param array $retData
	 * @return bool
	 * @throws \Exception
	 */
	protected function verifySign(array $retData){
		$retSign = $retData['sign'];//先不验证加密
		return true;
		$data = ArrayUtil::removeKeys($retData, ['sign']);

		$values = [
			'return_code'        => $data['code'],
			'return_msg'         => $data['msg'],
			'out_trade_no'       => $data['outTradeNo'],
			'transaction_id'     => $data['transactionId'],
			'pay_type'           => $data['payType'],
			'total_fee'          => $data['totalAmount'],
			'user_id'            => $data['buyerId'],
			'out_transaction_id' => $data['outTransactionId'],
		];

		$values = ArrayUtil::paraFilter($values);
		//        $values = ArrayUtil::arraySort($values);
		$signStr = ArrayUtil::createLinkstring($values);

		switch($this->config->signType){
			case 'MD5':
				$sign = md5($signStr);
				break;
			default:
				$sign = '';
		}

		return strtoupper($sign) === strtoupper($retSign);
	}

    /**
     * 向客户端返回必要的数据
     *
     * @param array $data
     * @return array
     */
	protected function getRetData(array $data){
		// TODO: Implement getRetData() method.
        return [
            'return_code'        => $data['code'],
            'return_msg'         => $data['msg'],
            'out_trade_no'       => $data['outTradeNo'],
            'transaction_id'     => $data['transactionId'],
            'pay_type'           => $data['payType'],
            'total_fee'          => $data['totalAmount'],
            'user_id'            => $data['buyerId'],
            'out_transaction_id' => $data['outTransactionId'],
            'pay_time'           => $data['payTime'],
            'channel'            => Config::LTF_CHARGE,
        ];
	}

	/**
	 * 根据返回结果，回答支付机构。是否回调通知成功
	 *
	 * @param boolean $flag 每次返回的bool值
	 * @param string  $msg 通知信息，错误原因
	 * @return mixed
	 */
	protected function replyNotify($flag, $msg = 'OK'){
		return ($flag ? true : false);
		// TODO: Implement replyNotify() method.
	}
}
